package com.bsj.media.media;

import com.bsj.media.media.G726.G726_32k;
import com.bsj.media.media.G726.g726_state_s;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AudioDecorder2 {



	private int audioType; // 解码器类型
	private boolean isInit; // 是否初始化
	private int nb_samples; // 样本数
	private g726_state_s g726State; // G726解码对象

	public AudioDecorder2() {
		super();
		this.isInit = false;
	}

	/**
	 * 初始化音频解码器
	 * 
	 * @param audioType
	 *            音频类型，与FDFD协议设置相对应0 adpcm_ima, 1 g711a ,2 g726
	 * @param nchannels
	 *            声道数 单声道 设备
	 * @param nsample_rate
	 *            采样率 8000 设备
	 * @return
	 */
	public boolean init(int audioType, int nchannels, int nsample_rate) {

		if (audioType != 0 && audioType != 1 && audioType != 2) {
			log.error("不支持编码类型：" + audioType);
			return false; // Codec not found
		}

		if (audioType == 2) {
			g726State = G726_32k.g726_init();
			if (g726State == null) {
				log.info("初始化G726对象失败！");
				return false;
			}
		}

		log.info("====音频类型：" + audioType);
		this.audioType = audioType;
		isInit = true;
		return true;
	}

	/**
	 * 解码g711数据
	 * 
	 * @param buffer
	 *            音频数据
	 * @param offset
	 *            g711数据在真个音频数据中的偏移位置
	 * @param length
	 *            g711数据长度
	 * @return pcm帧
	 */
	public int DecoderSamples(byte[] buffer, int offset, int length, byte[] pcm) {

		if (!isInit) {
			return 0;
		}

		int pcmSize = 0;
		if (audioType == 0) {
			// adpcm
			pcmSize = Adpcm.decoder(buffer, offset, length, pcm);
			nb_samples = 321;
		} else if (audioType == 1) {
			// g711a
			pcmSize = G711A.decoder(buffer, offset, length, pcm);
			nb_samples = 320;
		} else {
			// g726_32k
			pcmSize = G726_32k.decoder(g726State, pcm, buffer, offset, length);
			nb_samples = 320;
		}

		return pcmSize;
	}

	public boolean isInit() {
		return isInit;
	}

	public void setInit(boolean isInit) {
		this.isInit = isInit;
	}

	public int getNb_samples() {
		return nb_samples;
	}

	public void setNb_samples(int nb_samples) {
		this.nb_samples = nb_samples;
	}
}
